"use strict";
// https://api.nevegy.com/manage/single/devicesetting.html?edit=update&type=2&locid=1000&devid=197
// https://api.nevegy.com/manage/single/devicesetting.html?edit=update&type=3&locid=1000&devid=15

const backautoTemp = function (val: any) {
  return `
<label for="">
  <input type="time" class="form-control" value="${val}">
  <button type="button" class="btn btn-danger backatuoRemove">-</button>
</label>
`;
};
const group1 = [300, 301, 302];
const group2 = [200, 201, 202];
const group3 = [1, 2, 3, 4, 5, 6];
let selArr: any = [];
setLan();
getType2(urlParma);

function getType2(params: any) {
  const {devid, locid, type} = params;
  axios({
    method: 'post',
    url: 'https://api.nevegy.com/index.php/api/manage?mtd=GetInfoByToken',
    data: {
      devId: devid,
      type: type,
      locationId: locid,
    }
  })
    .then(function (response: any) {
      type2(response.data.data);
    });
}

function type2(data: any) {
  console.log(data);
  let typeOption: any;
  if (urlParma.type === '2') {
    typeOption = subtype2;
    $('#deviceSubType').attr('disabled', true);
  }
  if (urlParma.type === '3') {
    typeOption = subtype3;
  }
  $('#deviceSubType option').each((i: any, item: any) => {
    if (typeOption.indexOf(Number(item.value)) === -1) {
      $(item).remove();
    }
  });
  $('#deviceSubType').on('change', (event: any) => {
    checksubtypeGroup(event.target);
  });
  $('#addBackAuto').on('click', (event: any) => {
    $('.backauto').append($(backautoTemp('00:00')));
  });
  $('body').on('click', '.backatuoRemove', (event: any) => {
    const dom = event.target;
    $(dom).parent().remove();
  });
  const {area_info, device_info, location_info} = data;
  let deviceinfo = device_info.filter((item: any) => Number(item.id) === Number(urlParma.devid))[0];
  $('#locationDevice option').eq(0).val(location_info.id);
  $('#locationDevice option').eq(0).text(location_info.nameEn);
  $('#locationDevice').val(location_info.id);
  if (deviceinfo) {
    let {
      s1state,
      s1name,
      s1t1mode,
      s1t1on,
      s1t1off,
      s1t2mode,
      s1t2on,
      s1t2off,
      s1t3mode,
      s1t3on,
      s1t3off,
      details,
      s2state,
      s2name,
      s2t1mode,
      s2t1on,
      s2t1off,
      s2t2mode,
      s2t2on,
      s2t2off,
      s2t3mode,
      s2t3on,
      s2t3off
    } = deviceinfo;
    if (urlParma.type === '2') {
      $('#deviceName').val(deviceinfo.dname);
      $('#passDevice').val(deviceinfo.pass);
      $('#deviceMac').val(deviceinfo.mac);
      $('#areaDevice').html(area_info.map((item: any) => `<option value="${item.id}">${item.nameEn}</option>`));
      const weekdom: any = Array.from(document.querySelectorAll('[name="deviceDays"]'));
      deviceinfo.weekdays.split('').map((item: any, index: any) => {
        weekdom[index].checked = Number(item) === 1;
      });
    } else if (urlParma.type === '3') {
      $('#deviceName').val(deviceinfo.f_name);
      $('#passDevice').val(deviceinfo.f_pass);
      $('#deviceMac').val(deviceinfo.f_mac);
      $('#areaDevice').html(area_info.map((item: any) => `<option value="${item.id}">${item.aname}</option>`));
    }
    Array.from(document.querySelectorAll('.time select')).map((item) => {
      toggleTime(item);
      item.addEventListener('change', (event) => {
        toggleTime(event.target);
      });
    });
    $('#deviceStatus').val(deviceinfo.status);
    $('#deviceSubType').val(deviceinfo.subtype);
    // port 1
    $('#flexSwitchCheckOne').attr('checked', Number(s1state) !== 0);
    $('#port1Name').val(s1name);
    $('#switchModeP1T1').val(s1t1mode);
    toggleTime(document.querySelector('#switchModeP1T1'));
    $('#port1Timer1Start').val(transToTime(String(s1t1on)));
    $('#port1Timer1End').val(transToTime(String(s1t1off)));
    $('#switchModeP1T2').val(s1t2mode);
    toggleTime(document.querySelector('#switchModeP1T2'));
    $('#port1Timer2Start').val(transToTime(String(s1t2on)));
    $('#port1Timer2End').val(transToTime(String(s1t2off)));
    $('#switchModeP1T3').val(s1t3mode);
    toggleTime(document.querySelector('#switchModeP1T3'));
    $('#port1Timer3Start').val(transToTime(String(s1t3on)));
    $('#port1Timer3End').val(transToTime(String(s1t3off)));
    // port 2
    $('#flexSwitchCheckTwo').attr('checked', Number(s2state) !== 0);
    $('#port2Name').val(s2name);
    $('#switchModeP2T1').val(s2t1mode);
    toggleTime(document.querySelector('#switchModeP2T1'));
    $('#port2Timer1Start').val(transToTime(String(s2t1on)));
    $('#port2Timer1End').val(transToTime(String(s2t1off)));
    $('#switchModeP2T2').val(s2t2mode);
    toggleTime(document.querySelector('#switchModeP2T2'));
    $('#port2Timer2Start').val(transToTime(String(s2t2on)));
    $('#port2Timer2End').val(transToTime(String(s2t2off)));
    $('#switchModeP2T3').val(s2t3mode);
    toggleTime(document.querySelector('#switchModeP2T3'));
    $('#port2Timer3Start').val(transToTime(String(s2t3on)));
    $('#port2Timer3End').val(transToTime(String(s2t3off)));
    checksubtypeGroup(document.querySelector('#deviceSubType'));
    // details = { "cd": 1, "rd": 1, "auto": "$1000$$1100$" }
    if (typeof details === 'string') {
      details = JSON.parse(details);
    }
    if (details) {
      if (urlParma.type === '2') {
        $('#cooldown').val(details.cd);
        $('#radar').val(details.rd);
      }
      if (urlParma.type === '3') {
        $('#temperature').val(details.tc);
        $('#humidity').val(details.hc);
        $('#screensaver').val(details.sbt);
      }
      if (String(details.auto).match(/\$/)) {
        const auto = details.auto.split('$').filter((item: any) => item);
        let html = auto.map((item: any) => backautoTemp(transToTime(String(item)))).join('');
        $('.backauto').html(html);
      }
    }
  }
  $('#btn_create').on('click', function () {
    const {devid, locid} = urlParma;
    const areaId = $('#areaDevice').val();
    const deviceName = $('#deviceName').val();
    const deviceMac = $('#deviceMac').val();
    const deviceSubType = $('#deviceSubType').val();
    const password = $('#passDevice').val();
    const passwordNew = $('#passDeviceNew').val();
    const deviceStatus = $('#deviceStatus').val();
    const weekdays = Array.from(document.querySelectorAll('[name="deviceDays"]')).map((item: any) => {
      return item.checked ? 1 : 0;
    }).join('');
    const s1name = $('#port1Name').val();
    const t1mode = $('#switchModeP1T1').val();
    const t1on = Number($('#port1Timer1Start').val().split(':').join(''));
    const t1off = Number($('#port1Timer1End').val().split(':').join(''));
    const t2mode = $('#switchModeP1T2').val();
    const t2on = Number($('#port1Timer2Start').val().split(':').join(''));
    const t2off = Number($('#port1Timer2End').val().split(':').join(''));
    const t3mode = $('#switchModeP1T3').val();
    const t3on = Number($('#port1Timer3Start').val().split(':').join(''));
    const t3off = Number($('#port1Timer3End').val().split(':').join(''));
    const tempCallibration = Number($('#temperature').val());
    const humCallibration = Number($('#humidity').val());
    const screenSaverTime = Number($('#screensaver').val());
    let backAuto = '';
    $('.backauto label').each(function (i: any, item: any) {
      let val = $(item).children('input').val();
      val = `$${val.split(':').join('')}$`;
      backAuto += val;
    });
    // if ([300, 301, 302].indexOf(Number($('#deviceSubType').val())) !== -1) {
    const s2name = $('#port2Name').val();
    const s2t1mode = $('#switchModeP2T1').val();
    const s2t1on = Number($('#port2Timer1Start').val().split(':').join(''));
    const s2t1off = Number($('#port2Timer1End').val().split(':').join(''));
    const s2t2mode = $('#switchModeP2T2').val();
    const s2t2on = Number($('#port2Timer2Start').val().split(':').join(''));
    const s2t2off = Number($('#port2Timer2End').val().split(':').join(''));
    const s2t3mode = $('#switchModeP2T3').val();
    const s2t3on = Number($('#port2Timer3Start').val().split(':').join(''));
    const s2t3off = Number($('#port2Timer3End').val().split(':').join(''));
    const cooldown = Number($('#cooldown').val());
    const rd = Number($('#radar').val());
    let submitParams = {};
    if (urlParma.type === '2') {
      submitParams = {
        // token,
        act: "upd",
        type: "2",
        locationId: locid,
        devId: devid,
        areaId,
        deviceName,
        deviceMac,
        deviceSubType,
        password,
        passwordNew,
        deviceStatus,
        weekdays,
        s1name,
        t1mode,
        t1on,
        t1off,
        t2mode,
        t2on,
        t2off,
        t3mode,
        t3on,
        t3off
      };
      if ([300, 301, 302].indexOf(Number($('#deviceSubType').val())) !== -1) {
        submitParams = Object.assign(submitParams, {
          s2name,
          s2t1mode,
          s2t1on,
          s2t1off,
          s2t2mode,
          s2t2on,
          s2t2off,
          s2t3mode,
          s2t3on,
          s2t3off,
          cooldown,
          rd,
          backAuto
        });
      }
    }
    if (urlParma.type === '3') {
      submitParams = {
        // token,
        act: "upd",
        type: "3",
        locationId: locid,
        devId: devid,
        areaId,
        deviceName,
        deviceMac,
        deviceSubType,
        password,
        passwordNew,
        deviceStatus,
        tempCallibration,
        humCallibration,
        screenSaverTime,
        backAuto
      };
    }
    console.log(submitParams);
    // return;
    axios({
      method: 'post',
      url: 'https://api.nevegy.com/index.php/api/manage?mtd=ModifyDevices',
      // url: 'https://api.nevegy.com/index.php/api/manage?mtd=GetInfoByToken',
      data: submitParams
    })
      .then(function (response: any) {
        console.log(response);
        dialogObj.ok();
        $('#dialog p').html('Successfully!');
        if (!response.data.status) {
          $('#dialog p').html(response.data.msg);
          dialogObj.no();
        }
        dialogObj.open();
      })
      .catch(function (error: any) {
        console.log(error);
        dialogObj.no();
        $('#dialog p').html('Failed!!!');
        dialogObj.open();
      });
  });
}

function checksubtypeGroup(dom: any) {
  let lan = GetQueryString('lan') || 'en';
  if (!transLan.hasOwnProperty(lan))
    lan = 'en';
  let optg1 = ['OFF', 'ON', 'Switch', 'Sensor', 'Disabled'].map((item) => transLan[lan][item]);
  let optg2 = ['OFF', 'ON', 'Switch only', 'Sensor only', 'Switch & Sensor', 'Disabled'].map((item) => transLan[lan][item]);
  $('.time select').each(function (i: any, sel: any) {
    // let val = sel.value;
    selArr[i] = sel.value;
    let opthtml: any = [];
    // [1, 2, 3, 4, 5, 6]
    if (group3.indexOf(Number(dom.value)) !== -1) {
      opthtml = optg1;
      if (sel[i] === '4')
        sel[i] = '1';
    }
    // [300, 301, 302]
    if (group1.indexOf(Number(dom.value)) !== -1) {
      opthtml = optg2;
      if (sel[i] === '4')
        sel[i] = '5';
    }
    $(sel).html(opthtml.map((item: any, index: any) => `<option value="${index}">${item}</option>`).join('')).val(selArr[i]);
  });
  document.querySelector('.week')?.classList.toggle('show', [...group2].indexOf(Number(dom.value)) === -1);
  document.querySelector('.port1')?.classList.toggle('show', [...group1, ...group3].indexOf(Number(dom.value)) !== -1);
  document.querySelector('.port2')?.classList.toggle('show', group1.indexOf(Number(dom.value)) !== -1);
  document.querySelector('.cooldown')?.classList.toggle('show', group1.indexOf(Number(dom.value)) !== -1);
  document.querySelector('.radar')?.classList.toggle('show', group1.indexOf(Number(dom.value)) !== -1);
  document.querySelector('.backautobox')?.classList.toggle('show', [...group2, ...group1].indexOf(Number(dom.value)) !== -1);
  document.querySelector('.Temperature')?.classList.toggle('show', group2.indexOf(Number(dom.value)) !== -1);
  document.querySelector('.humidity')?.classList.toggle('show', group2.indexOf(Number(dom.value)) !== -1);
  document.querySelector('.screensaver')?.classList.toggle('show', group2.indexOf(Number(dom.value)) !== -1);
}

function toggleTime(dom: any) {
  const subtype = $('#deviceSubType').val();
  let disabled = '4';
  if (group1.indexOf(Number(subtype)) !== -1) {
    // console.log(group1, subtype)
    disabled = '5';
  }
  let disArr = ['0'];
  if ([1, 2, 3, 4, 5, 6].includes(Number(subtype))) {
    disArr = ['0', String(disabled)];
  }
  if (disArr.includes(String(dom.value))) {
    $(dom).siblings().removeClass('visible');
  } else {
    $(dom).siblings().addClass('visible');
  }
}
